package com.gyz.cfmall.controller;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author gong_yz
 * @Description
 * @Date 2023/4/14
 */
@Controller
public class LoginController {

    @Resource
    private StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String url, Model model) {

        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 处理登录请求
     *
     * @return
     */
    @GetMapping("/doLogin")
    public String doLogin(@RequestParam("userName") String userName,
                          @RequestParam("passWord") String passWord,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {

        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(passWord)) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, userName);
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:" + url + "?token=" + uuid;
        }
        return "login";
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token) {
        String info = redisTemplate.opsForValue().get(token);
        return info;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + url + "?token=" + sso_token;
        }

        model.addAttribute("url", url);
        return "login";
    }
}
